// pages/account/invite/index.js
const account = require("../../../js/modules/account.js");
const info = require("../../../js/modules/info.js");
import {dialog,api,util,forms,storage,clickIncrement} from '../../../js/util';
import {config} from "../../../js/modules/gloab";
import BasePage from '../../../js/common/base-page'
import {
  router
} from '../../../js/router'
var app = getApp();
BasePage({
  validateLogin: false,
  /**
   * 页面的初始数据
   */
  data: {
    forms: {
      Name: {
        value: "",
        validate: "isnull",
        error: "请输入您的名称"
      },
      Mobile: {
        value: "",
        validate: "isnull|mobile",
        error: "请输入正确的手机号"
      },
      PicVerifyCode: {
        value: "",
        validate: "isnull",
        error: "请输入正确的图片校验码"
      },
      ValidateCode: {
        value: "",
        validate: "isnull",
        error: "请输入正确的短信校验码"
      },
      Password: {
        value: "",
        validate: "isnull|pwd",
        error: "请输入正确的密码，密码只能是6~20位英文、数字或者下划线以及点"
      },
      IsAgree:{
        value: false,
        fixed: true,
        validate: "isnull",
        error: "请阅读并同意服务协议和隐私政策"
      },
      qr:{
        value:"",
        validate: "isnull",
        error: ""
      }
    },
    // 登录后供应商信息
    supplier: {
      "display": "none", // 多供应商列表显示
      "list": [] // 待选供应商列表
    },
    inviteType: 0,//0-分销名片 1-订货码
    scene: '',
    totleHeight: '603px',
    headerBg:'',
    inviteInfo:{},
    siteName:'',
    shadowTitle:'服务协议',
    role: "store", // 当前页面登录角色
    imgDomain:api.imgDomain,
    enableOss: api.enableOss,
    wxRegisterAndLogin:true,//微信是否登录
    loginType:0,//登录方式
    isEnableLogin: false,
    customize: {  // 填写名称相关控制信息
      Required: 1,
      Status: 1
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    let scene = options.scene||'1_0_0';
    console.log('invite-options', options);
    this.setData({
      scene: scene,
      inviteType: scene.indexOf('_')==-1 ? 1 : 0
    });
    if (scene.indexOf('_')==-1) {
      //新版订货码
      account.register.getInviteInfo(scene,function(status, res){
        if (status) {
          //判断过期时间
          if (res.ExpireTime != null && res.ExpireTime != undefined && res.ExpireTime != "") {
            if (new Date().getTime() < new Date(res.ExpireTime).getTime()) {
              that.setData({
                isEnableLogin: true,
                inviteInfo:res
              });
            }else{
              util.tips("此订货码已过期！");
              that.setData({
                isEnableLogin: false,
                inviteInfo:res
              });
            }
          }
        }else{
          util.alert(res);
        }
      });
    }else{
      //旧版分销名片
      this.data.forms["qr"].value=scene
      //获得图片验证码组件
      this.picVerifyCode = this.selectComponent("#picVerifyCode");
      //设置回调
      this.picVerifyCode.data.callback = info.getPicVerifyCode;
      //调用一次图片验证码
      this.picVerifyCode.bindPicVerifyCode();
      //获得发送短信组件
      this.smsVerifyCode = this.selectComponent("#smsVerifyCode");
      //设置回调
      this.smsVerifyCode.data.callback = this.bindSmsVerifyCode;
      account.register.getCardAccount(scene,function(status, res){
        if (status) {
          console.log('card-info', res);
          that.setData({
            inviteInfo:res
          });
        }else{
          util.alert(res);
        }
      });
      this.getWholesaleConfig();
    }
    //计算协议高度
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          totleHeight: res.windowHeight + 'px'
        });
      }
    });
    wx.login({
      success: res =>{
          this.data.code = res.code
      }
    });
    this.getCustomize()
  },
  /**
   * 获取服务协议
   */
  getProtocol:function(){
    let that = this;
    account.register.getProtocol(that.data.role,function(res){
      let content;
      if(app.dns.proprietor == app.dns.fkFlag){
        content = res
      }else{
        content = res.Content.JoinProtocol;//.replace(/<br\s*\/?>/gi, "\n").replace(/(^\s*)|(\s*$)/g, "\t");
      }
      that.setData({
        shadowTitle:'服务协议',
        richtext_content: content
      })
      that.showModal();
    })
  },
  /**
   * 获取隐私政策
   */
  getPrivacy:function(){
    let that = this;
    account.register.getPrivacy(function(res){
      that.setData({
        shadowTitle:'隐私政策',
        richtext_content: res
      },()=>{
        that.showModal();
      })
    })
  },
  /**
   * 校验手机号 
   * */
  bindValidateUserName: function() {
    var that = this;
    // 设置能否发送短信校验码为false
    that.smsVerifyCode.data.isSendSmsCode = false;
    that.data.mobileToken = "";
    that.data.mobileMsg = "";
    var mobile = that.data.forms.Mobile;
    //验证手机号
    if (!forms.validate(mobile)) return false;

    //组装参数
    var param = {
      mobile: mobile.value,
      ProprietorId: app.dns.proprietorId,
      ZoneId: app.dns.zoneId
    };

    account.register.validateUserName("store",param,
      function(res) {
        if (res.Success) {
          that.data.mobileToken = res.Content;
          that.smsVerifyCode.data.isSendSmsCode = false;
        } else {
          //that.smsVerifyCode.data.isSendSmsCode = true;
          that.data.mobileMsg = res.Message;
          util.tips(res.Message,3000);
          return;
        }
      });
  },
  /*
  发送短信验证码
   */
  bindSmsVerifyCode: function(callback) {
    var mobile = this.data.mobileToken,
        mobileMsg = this.data.mobileMsg;
    if(mobileMsg!==''){
      util.alert(mobileMsg);
      return;
    };
    if (mobile == undefined || mobile.length == 0) {
      util.alert("手机号未验证成功");
      return;
    }
    var picvalidatecode = this.data.forms.PicVerifyCode.value;
    if (picvalidatecode.length == 0) {
      util.alert("请先输入4位验证码");
      return;
    }
    var codeToken = storage.get("pic_verify_code");
    if (codeToken == undefined || codeToken.length == 0) {
      util.alert("图片验证码过期");
      return;
    }
    var dir = storage.get("LoginSessionVirtualDirKey")||'';
    var data = {
      mobile: mobile,
      verifyCode: picvalidatecode,
      codeToken: codeToken,
      proprietorId: app.dns.proprietorId,
      code:dir
    };
    info.sms.getSmsVerifyCode(data, "account.store.validatecode.get", function (content) {
      if (callback && typeof (callback) == "function") {
        callback(content);
      }
    });
  },
  /**是否同意服务条款 */
  checkboxChange(e) {
    if (this.data.forms.IsAgree.value) {
      this.data.forms.IsAgree.value = false;
    } else {
      this.data.forms.IsAgree.value = true;
    }
    this.setData({ forms: this.data.forms });
  },
    /*
  注册
   */
  register: function(e) {
    var that = this;
    let {
      customize,
      forms
    } = this.data
    clickIncrement( ()=> {
      // 当非必填或未显示输入名称时，不校验名称是否填写
      if (customize.Status != 1 || customize.Required != 1) {
        forms.Name.validate = ''
      }
      if (that.data.isSubmitOrder) return;
      that.setData({
        isSubmitOrder: true
      });
      account.register.submit("store", forms, '', (s)=>{
        if(s==false){
          that.setData({
            isSubmitOrder: false
          });
        }
      });
    });
  },
   /**微信一键授权登录-绑定用户信息 */
  onAuthLogin: function(e) { 
    var that = this;
    if (that.data.isExcuting) return;
    if (e.detail.errMsg.indexOf("fail auth deny") > -1 || e.detail.userInfo == undefined) {
      return;
    }
    if (!this.data.forms.IsAgree.value) {
      util.alert("请阅读并同意服务协议和隐私政策");
      return;
    }
    that.setData({
      isExcuting: true
    });
    var userInfo = {};
    userInfo["code"]=that.data.code;
    userInfo["iv"]=e.detail.iv;
    userInfo["qr"]=that.data.scene;
    userInfo["encryptedData"]=e.detail.encryptedData;
    account.login.saveAuthInfo(that.data.role, userInfo, function(res) {
      //跳转
      router.redirect({
        path: "phoneauth",
        params:{
          role: that.data.role,
          WxUserId:res.WxUserId,
          OfficialUserId:res.OfficialUserId,
          unionId:res.unionId,
        }
      });
    }, (bo, token, virtualPath) => {
      this.success(bo, token, virtualPath);
      that.setData({
        isExcuting: false
      });
    });
  },
  /**微信一键授权登录-绑定用户信息 */
  onBindPhone: function(e) {
    var that = this;
    if (!this.data.forms.IsAgree.value) {
      util.alert("请阅读并同意服务协议和隐私政策");
      return;
    }
    if (that.data.isExcuting) return;
    if (e.detail.errMsg.indexOf("getPhoneNumber:ok") == -1) {
      console.log(e.detail,'=====提示')
      return;
    }
    that.setData({
      isExcuting: true
    });
    var userInfo =e.detail || {};   
    userInfo["qr"]=that.data.scene;
    userInfo["code"]=that.data.code;
    app.getOpenId('',function(contet){
      if(!contet.Success){
        util.tips(contet.Message);
        that.setData({
          isExcuting: false
        });
        return
      }
      var content = contet.Content || {};
      userInfo["openid"]=content.openid;
      userInfo["unionid"]=content.unionid;
      userInfo['OfficialId'] = content.OfficialId;
      account.login.onAuthLoginVerify(that.data.role, userInfo, function(res) {
        console.log('callback1', res)
        //展示弹出层
        that.setData({
          supplier: {
            "display": 'block',
            list: res.Content,
            isExcuting: false
          }
        });
      }, (bo, token, virtualPath) => {
        console.log('callback2', bo, token, virtualPath)
        that.success(bo, token, virtualPath);
        that.setData({
          isExcuting: false
        });

      }, that);
    })
  },
  /*选择商家登录 */
  select_login: function(e) {
    var that = this;
    var token = e.currentTarget.dataset.token;
    account.login.login(this.data.role, token, (bo, token, virtualPath)=> {
      this.success(bo, token, virtualPath);
      that.setData({
        isExcuting: false
      });
    });
  },
  /**登录成功后 */
  success(bo, token, virtualDir) {
    if (bo) {
      router.switchTab({
        path: "index",
      }); 
      // let role=authorize.loginRole();
      // if(role=="store"){
      //   router.switchTab({
      //     path: "index", 
      //   });
      //   return;
      // }
      // let backUrl = this.data.backUrl||"";
      // backUrl = backUrl == "undefined" ? "" : backUrl;

      // backUrl=(role=="supplier"?"#/supplier/admin":"#/clerk");

      // router.redirect(
      //   {
      //     path: "pages/common/container/index",
      //     params: {
      //       action: "skip",
      //       token: token,
      //       role: role,
      //       hashPath: backUrl
      //     }
      //   });
    }
    else if(token==40029){
      wx.login({
        success: res =>{
            this.data.code = res.code
        }
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      headerBg: api.titleColor||"#e56b14",
      mainColor: api.titleColor||"#e56b14"
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 表单值绑定
   */
  bindFormValue: function(e) {
    e = e.detail;
    this.data.forms[e.target.id].value = e.detail.value;
  },
  /**加载商品类的配置项参数 */
  getWholesaleConfig() {
      var that = this;
      var fkid = app.dns.proprietorId;
      var fkflag = app.dns.proprietor;
      config.getWholesaleConfigs(
      fkid,
      fkflag,
      "Wholesale",
      function (model) {
        that.setData({
          siteName:model.SiteName
        });
      });
      config.getConfig(
        fkid,
        fkflag,
        'Roles',
        'StoreSetting',
        function(res) {
          if (res && res.Success) {
            var content = res.Content;
            that.setData({
              wxRegisterAndLogin: content.WXRegisterAndLogin,
              loginType: content.LoginType || 0
            });
          }
        });
    },
   /**
   * 显示遮罩层
   */
  showModal: function (evt) {
    dialog.showModal(this, 'showModalStatus')
  },
  /**
   * 隐藏遮罩层
   */
  hideModal: function () {
    dialog.hideModal(this, 'showModalStatus')
  },
  /**
   * 获取自定义表单设置（名称）
   */
  getCustomize: function () {
    let that = this;
    account.register.getCustomize(function (res) {
      that.setData({
        customize: res.Content
      })
    })
  },
})